package com.platform.cdcs.fragment;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.MyApp;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.detail.InOutTicketFragment;
import com.platform.cdcs.fragment.detail.LineTicketFragment;
import com.platform.cdcs.fragment.detail.ProductBelongFragment;
import com.platform.cdcs.fragment.detail.ProductTicketFragment;
import com.platform.cdcs.fragment.stock.InStockFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.model.SubBUItem;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.platform.cdcs.widget.ChooseWindow;
import com.trueway.app.uilib.activity.BackListener;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/11/1.
 */
public class WebFragment extends BaseFragment {

    private String title;
    private WebView webView;
    private String linkUrl;
    private String mClass;
    private List<ChooseItem> subBuList;
    private List<ChooseItem> productList;
    private String subBU = "", subBUName = "";
    private String productName = "", productCode = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            title = getArguments().getString("title", "");
            linkUrl = getArguments().getString("url", "");
            mClass = getArguments().getString("class", "");
        }
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        setTitle(title);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    getActivity().finish();
                }
            }
        });
        webView = new WebView(getContext());
        webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        RelativeLayout rootView = (RelativeLayout) view.findViewById(R.id.root);
        rootView.addView(webView);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoadImg();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dismissLoadImg();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    return true;
                } else if (url.startsWith("https://mp.weixin.qq.com")) {
                    ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                    if (!ViewTool.isInstalled(getActivity(), comp)) {
                        Utils.showToast(getContext(), "请先安装微信");
                    } else {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setComponent(comp);
                        startActivity(intent);
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
        });

        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportMultipleWindows(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.addJavascriptInterface(this, "OS");
        webView.loadUrl(linkUrl);
        addBackListener(new BackListener() {
            @Override
            public void onBackListener() {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    getActivity().finish();
                }
            }
        });
    }

    private RefershEvent getEvent() {
        RefershEvent event = new RefershEvent();
        try {
            event.mclass = Class.forName(mClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return event;
    }

    @JavascriptInterface
    public void command(final String data) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject obj = new JSONObject(data);
                    String cmd = obj.getString("cmd");
                    if (mClass.contains("CustomProFragment")) {
                        if ("delete".equals(cmd)) {
                            EventBus.getDefault().post(getEvent());
                        } else if ("regNumber".equals(cmd)) {

                        } else if ("priceList".equals(cmd)) {

                        }
                    } else if (mClass.contains("AccountListFragment")) {
                        if ("delete".equals(cmd)) {
                            EventBus.getDefault().post(getEvent());
                        }
                    } else if (mClass.contains("StockListFragment")) {
                        if ("delete".equals(cmd)) {
                            EventBus.getDefault().post(getEvent());
                        }
                    } else if (mClass.contains("StockInfoFragment")) {
                        if ("chooseType".equals(cmd)) {
                            //选择产品型号
                            showChooseTypeWindow();
                        } else if ("chooseLine".equals(cmd)) {
                            //选择产品线
                            showChooseSubBUWindow();
                        } else if ("click".equals(cmd)) {
                            JSONObject param = obj.getJSONObject("param");
                            int index = param.getInt("index") - 1;
                            Bundle bundle = new Bundle();
                            bundle.putString("stockId", getArguments().getString("stockId"));
                            bundle.putInt("inType", index);
                            bundle.putString("subBUs", subBU);
                            bundle.putString("itemCodes", productCode);
                            FragmentUtil.navigateToInNewActivity(getActivity(), InStockFragment.class, bundle);
                        } else if ("reset".equals(cmd)) {
                            subBU = null;
                            subBUName = null;
                            productCode = null;
                            productName = null;
                        }
                    } else if ("产品详情".equals(title)) {
                        if ("click".equals(cmd)) {
                            JSONObject param = obj.getJSONObject("param");
                            int index = param.getInt("index");
                            if (1 == index) {
                                //产品归属
                                FragmentUtil.navigateToInNewActivity(getActivity(), ProductBelongFragment.class, null);
                            } else if (2 == index) {
                                //发票
                                FragmentUtil.navigateToInNewActivity(getActivity(), ProductTicketFragment.class, null);
                            } else if (3 == index) {
                                //出入库单
                                FragmentUtil.navigateToInNewActivity(getActivity(), InOutTicketFragment.class, null);
                            } else {
                                //产品轨迹
                                FragmentUtil.navigateToInNewActivity(getActivity(), LineTicketFragment.class, null);
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.removeAllViews();
            webView.clearHistory();
            webView.destroy();
            webView = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int layoutId() {
        return R.layout.webview;
    }

    private void requestSubBu(final boolean flag) {
        showLoadImg();
        HashMap map = new HashMap<String, String>();
        map.put("stockId", getArguments().getString("stockId"));
        getHttpClient().post().url(Constant.DIST_ITEMCODESUBBU_LST).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getActivity() == null) {
                        return;
                    }
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<SubBUItem.SubBUList>>() {
                    }.getType();
                    BaseObjResponse<SubBUItem.SubBUList> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {

                        subBuList = new ArrayList<ChooseItem>();
                        ChooseItem item = new ChooseItem();
                        item.setTitle("全部产品线");
                        item.setTime("");
                        item.setIsCheck(true);
                        subBuList.add(item);
                        for (SubBUItem sub : response.getResult().getSubuList()) {
                            item = new ChooseItem();
                            item.setTitle(sub.getSubbuCode());
                            item.setTime(sub.getSubbuName());
                            subBuList.add(item);
                        }
                        productList = new ArrayList<ChooseItem>();
                        item = new ChooseItem();
                        item.setTitle("全部型号");
                        item.setTime("");
                        item.setIsCheck(true);
                        productList.add(item);
                        for (SubBUItem sub : response.getResult().getItemCodeList()) {
                            item = new ChooseItem();
                            item.setTitle(sub.getItemCode());
                            item.setTime(sub.getItemName());
                            productList.add(item);
                        }
                        if (flag) {
                            showChooseSubBUWindow();
                        } else {
                            showChooseTypeWindow();
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private void showChooseSubBUWindow() {
        if (subBuList == null) {
            requestSubBu(true);
        } else {
            final ChooseWindow window = new ChooseWindow(getContext());
            window.setData(subBuList, "产品线", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    window.dismiss();
                    subBU = window.getChoose();
                    subBUName = window.getChooseName();
                    reloadData();
                }
            });
            window.show(getActivity().findViewById(R.id.title));
        }
    }

    private void showChooseTypeWindow() {
        if (productList == null) {
            requestSubBu(false);
        } else {
            final ChooseWindow window = new ChooseWindow(getContext());
            window.setData(productList, "产品型号", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    window.dismiss();
                    productCode = window.getChoose();
                    productName = window.getChooseName();
                    reloadData();
                }
            });
            window.show(getActivity().findViewById(R.id.title));
        }
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == this.getClass()) {

        }
    }

    private void reloadData() {
        String productCodes = productCode;
        if (TextUtils.isEmpty(productCodes)) {
            productCodes = "";
        }
        String subBUs = subBU;
        if (TextUtils.isEmpty(subBUs)) {
            subBUs = "";
        }
        String url = String.format(Constant.SNAPSHOT_DETAIL, MyApp.getInstance().getAccount().getToken(), getArguments().getString("stockId"), productCodes, subBUs, URLEncoder.encode(productName), URLEncoder.encode(subBUName));
//        webView.goBack();
        webView.loadUrl(url);
        webView.clearHistory();

    }
}
